package.path = package.path..";./itemdb/?.lua"
require("curl")
require("xml")
DEFAULT_REALM = "Dalaran"

local download
do
	local temp
	local write = function (s, len)
		temp[#temp + 1] = s
		return len
	end
	function download(url)
		if VERBOSE then print("GET", url) io.flush() end
		temp = {}
		local c = curl.easy_init()
		c:setopt(curl.OPT_URL, url)
		c:setopt(curl.OPT_USERAGENT, "Firefox/2.0")
		if COOKIE then
			c:setopt(curl.OPT_HTTPHEADER, COOKIE)
		end
		c:setopt(curl.OPT_WRITEFUNCTION, write)
		local err, info = c:perform()
		if err ~= 0 then
			return
		else
			temp = table.concat(temp)
			if temp:len() > 0 then
				return temp
			end
		end
	end
end


local function getplayer(realm, name)
	local data = download(("http://eu.wowarmory.com/character-sheet.xml?r=%s&n=%s"):format(curl.escape(realm), curl.escape(name)))
	if data then
		f = io.open(name..".xml", "w")
		f:write(data)
		f:close()
		return xml.parse(data)
	end
end

--[[
-- a unit is declared as a table, having the following entries :

unit = {
	name = string,
	is_mob = boolean,
	is_dual_wielding = boolean,
	can_parry = boolean,
	can_block = boolean,
	
	level = number,
	class = string,
	race = string,

	agility = number,
	armor = number,
	
	defense_skill = number,
	weapon_skill = table,
	
	talent_weapon_bonus = table, -- skill
	talent_defense_bonus = number,
	talent_hit_bonus = number,
	talent_dodge_bonus = number,
	talent_parry_bonus = number,

	hit_rating = number,
	dodge_rating = number,
	weapon_rating = table,
	defense_rating = number,
	parry_rating = number,
	haste_rating = number,
}

]]
local function make_player_table(name, realm)
	realm = realm or DEFAULT_REALM
	local data = getplayer(realm, name)
	if not data then return end
	data = data:get_first_child("characterInfo")
	local result = {
		name = name,
		realm = realm,
		is_mob = false,
	}
	
	local char = data:get_first_child("character")
	result.level = tonumber(char:get_attribute("level"))
	result.class = char:get_attribute("class"):upper()
	result.race = char:get_attribute("race")
	local tab = data:get_first_child("characterTab")
	local stats = tab:get_first_child("baseStats")
	for node in stats:iterate_children() do
		result[node.label] = tonumber(node:get_attribute("effective"))
	end
	local defenses = tab:get_first_child("defenses")
	result.defense_skill = tonumber(defenses:get_first_child("defense"):get_attribute("value"))
	result.weapon_skill = {}

	-- result.hit_rating = 
	
	return result
end

local t = make_player_table("Jerryak")
for k, v in pairs(t) do
	print(k, v)
end
